package service

import (
	"context"
	"seichat/biz"
	"seichat/dao"
	"seichat/models"
)

type CommunityService interface {
	CreateCommunity(ctx context.Context, community *models.Community) error
	GetCommunityListByOwnerId(ctx context.Context, ownerId uint) (*[]models.Community, error)
	JoinCommunity(ctx context.Context, ownerId uint, cname string) error
}
type CommunityServiceImpl struct {
	communityDao dao.CommunityDao
	relationSvc  RelationService
	userSvc      UserService
}

func NewCommunityService(communityDao dao.CommunityDao, relationSvc RelationService, userSvc UserService) CommunityService {
	return &CommunityServiceImpl{
		communityDao: communityDao,
		relationSvc:  relationSvc,
		userSvc:      userSvc,
	}
}
func (c *CommunityServiceImpl) GetCommunityListByOwnerId(ctx context.Context, ownerId uint) (*[]models.Community, error) {
	//1. 校验用户是否存在
	if _, err := c.userSvc.FindUserById(ctx, ownerId); err != nil {
		return nil, err
	}
	//2.获取关系
	relations, err := c.relationSvc.GetRelationListByOwnerId(ctx, ownerId, 2)
	if err != nil {
		return nil, err
	}
	//3.获取群列表
	list, err := c.communityDao.GetCommunityListByRelations(ctx, relations)
	if err != nil {
		return nil, err
	}
	return list, nil
}

func (c *CommunityServiceImpl) CreateCommunity(ctx context.Context, community *models.Community) error {
	// 1. 校验群是否存在
	if _, ok := c.communityDao.CheckCommunityExist(ctx, community.Name); ok {
		return biz.AlreadyCommunity
	}
	//2.创建群聊
	if err := c.communityDao.CreateCommunity(ctx, community); err != nil {
		return err
	}
	return nil
}

func (c *CommunityServiceImpl) JoinCommunity(ctx context.Context, ownerId uint, cname string) error {
	//1. 校验群名是否存在
	community, ok := c.communityDao.FindCommunityByName(ctx, cname)
	if !ok {
		return biz.CommunityNotFound
	}
	//2.检查是否重复加群
	if _, ok = c.relationSvc.FindRelationByUserIdAndTargetId(ctx, ownerId, community.ID, 2); ok {
		return biz.AlreadyCommunity
	}
	//3.加群
	if err := c.communityDao.JoinCommunity(ctx, community.ID, ownerId, 2); err != nil {
		return err
	}
	return nil
}
